import torch
import torch.nn as nn
from torch import Tensor


class AlexNet(nn.Module):
    def __init__(self, num_classes=1000):
        super(AlexNet, self).__init__()
        # 输入图像：Nx1x56x56
        self.conv1 = nn.Conv2d(1, 32, kernel_size=3, stride=2, padding=1)
        # out: Nx32x28x28
        self.relu = nn.ReLU(inplace=True)
        self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
        # out: Nx32x14x14
        self.conv2 = nn.Conv2d(32, 96, kernel_size=3, padding=1)
        # out: Nx96x14x14
        # nn.ReLU(inplace=True)
        self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
        # out: Nx96x7x7
        self.conv3 = nn.Conv2d(96, 192, kernel_size=3, padding=1)
        # out: Nx192x7x7
        # nn.ReLU(inplace=True),
        self.conv4 = nn.Conv2d(192, 128, kernel_size=3, padding=1)
        # out: Nx128x7x7
        # nn.ReLU(inplace=True)
        self.conv5 = nn.Conv2d(128, 256, kernel_size=3, padding=1)
        # out: Nx128x7x7
        # nn.ReLU(inplace=True)
        self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2)
        # out: Nx256x3x3
        self.dropout = nn.Dropout()
        self.fc6 = nn.Linear(256 * 3 * 3, 1024)
        self.fc7 = nn.Linear(1024, 512)
        self.fc8 = nn.Linear(512, num_classes)

    def forward(self, x: Tensor) -> Tensor:
        x = self.conv1(x)
        x = self.relu(x)
        x = self.pool1(x)
        x = self.conv2(x)
        x = self.relu(x)
        x = self.pool2(x)
        x = self.conv3(x)
        x = self.relu(x)
        x = self.conv4(x)
        x = self.relu(x)
        x = self.conv5(x)
        x = self.relu(x)
        x = self.pool3(x)
        x = torch.flatten(x, 1)
        x = self.dropout(x)
        x = self.fc6(x)
        x = self.relu(x)
        x = self.dropout(x)
        x = self.fc7(x)
        x = self.relu(x)
        x = self.fc8(x)
        return x
